var poc_n = 0;
var poc_top_border = true;
var poc_fill_table = true;
var poc_allow_config = true;

var poc_msgframe_only;
if (localStorage.getItem ("po_clock_msgframe_only") == "true") {
    poc_msgframe_only = true;
} else {
    poc_msgframe_only = false;
}

function POCinstallClock () {
    // Add the control panel for sighting reporting.
    var cargo = document.getElementById ("cargo");
    if (!cargo) return;

    // Check if the stuff is already installed. If so, delete it first
    var tr = document.getElementById ("po_poc_clock");
    if (tr) tr.parentNode.removeChild (tr);

    try {
        var c = top.POGetClock ();
        poc_n = 0;
    } catch (ex) {
        poc_n ++;
        if (poc_n > 5) return;
        setTimeout (POCinstallClock, 100);
        return;
    }
    // Create a new row in the Status table and insert it
    tr = document.createElement ("tr");
    tr.id = "po_poc_clock";
    cargo.firstChild.insertBefore (tr, cargo.firstChild.lastChild);
    td = cargo.firstChild.childNodes[1].firstChild.cloneNode(false);
    tr.appendChild (td);
    td.id = "po_poc_clock_panel";
    
    POCreInstallClock ();
}

function POCinstallClockMsgframe () {
    // Install in msgframe only if NAV is not available
    var nav = top.frames[2];
    
    try {
        // Try is necessary in situations that there's a different domain loaded in the third frame
        if (nav && !poc_msgframe_only) {
            if (nav.location.href.indexOf("main.php") != -1) {
                var panel = document.getElementById ("po_poc_clock_panel");
                if (panel) {
                    panel.parentNode.removeChild (panel);
                }
                setTimeout (POCinstallClockMsgframe, 2000);
                return;
            }
        }
    } catch (ex) {}
    // Check if the clock is already installed
    if (document.getElementById ("po_poc_clock_panel")) {
        setTimeout (POCinstallClockMsgframe, 2000);
        return;
    }
    
    // Initialize the Clock subsystem
    try {
        var c = top.POGetClock ();
        poc_n = 0;
    } catch (ex) {
        poc_n ++;
        if (poc_n > 5) return;
        setTimeout (POCinstallClock, 100);
        return;
    }
    
    // Find the owning table
    var tbl = document.getElementById ("universe").parentNode.parentNode.parentNode.parentNode;
    
    // Set the existing cell sizes to that we can squeeze one more
    tbl.rows[0].cells[0].setAttribute ("width", "20%");
    tbl.rows[0].cells[1].setAttribute ("width", "35%");
    tbl.rows[0].cells[2].setAttribute ("width", "20%");
    
    // Create a new cell and put into the frame
    var td = document.createElement ("td");
    td.setAttribute ("width", "25%");
    td.id = "po_poc_clock_panel";
    tbl.rows[0].insertBefore (td, tbl.rows[0].cells[1]);
    
    var ths = document.getElementsByTagName ("th");
    var thb = null;
    for (var i=0; i<ths.length; i++) {
        if (ths[i].textContent == "Status") {
            tbl = ths[i].parentNode.parentNode.parentNode;
            break;
        }
    }
    poc_top_border = false;
    poc_fill_table = false;
    poc_allow_config = false;
    POCreInstallClock ();
    
    if (!poc_msgframe_only) {
        setTimeout (POCinstallClockMsgframe, 2000);
    }
}

var POClabels = {
    "getTime": "T:",
    "getGMT": "G:",
    "getAPS": "A:",
    "getBuildingTime": "B:",
    "getPLTime": "P:",
    "getStarbaseTime": "S:",
    "getNPCTime": "N:",
    "getLeechTime": "L:",
    "getACSTime": "C:",
    "getEMTime": "E:",
    "getLSMTime": "LM:",
    "getLSATime": "LA:",
	"getDruggyEff": "DReff:",
	"getDruggyTime": "D:"
}

function POCreInstallClock () {
    var clock = document.getElementById ('po_poc_clock_panel');
    if (!clock) return;
    var c = top.POGetClock ();
    var menu = document.getElementById ('poc_settings_panel');
    var set = POCgetSettings ();
    var realtime = true;
    if (set.indexOf ("realtime") == -1) realtime = false;
    set = set.split (";");

    var width = (poc_fill_table==true)?"width='100%'":"";
    var border = (poc_top_border==true)?"style='border-top:1px solid white'":"";
    var link = (poc_allow_config==true)?"<a href='javascript:POCshowSettings();void(0);' style='font-size:10px; font-weight:bold; color:lime'>Clock</a>":"<span style='font-size:10px; font-weight:bold; color:lime'>Clock</span>";

    clock.innerHTML = "<div style='margin:0px 18px; font-size:10px; font-weight:bold' >\
               <table "+border+" "+width+"><tbody>\
               <tr>\
                <td id='poc_first_cell'>"+link+"</td>\
               </tr></tbody></table></div>";
    var body = clock.getElementsByTagName ("tbody")[0];

    if (menu) {
        var td = document.getElementById ('poc_first_cell')
        td.insertBefore (menu, td.firstChild);
    }
    var no = 1;
    var row = body.rows[0];
    for (var i=0; i<set.length; i++) {
        if (set[i] == "realtime" || set[i] == "") continue;
        if (no == 4) {
            var tr = document.createElement ("tr");
            body.appendChild (tr);
            row = tr;
            no = 0;
        }
        var td = document.createElement ("td");
        row.appendChild (td);
        td.innerHTML = "<span style='font-size:10px; font-weight:bold'></span>";
        c.createTimeElement ("poc_nav_"+set[i], td.firstChild, set[i], true, true, realtime, POClabels[set[i]]);
        no ++;
    }
}

function POCshowSettings () {
    var menu = document.getElementById ("poc_settings_panel");
    if (menu) {
        menu.parentNode.removeChild (menu);
        return;
    }
    var set = POCgetSettings ();
    var menu = POdialogBox ();
    menu.id = "poc_settings_panel";
    var par = menu.rows[0].cells[0];
    par.innerHTML = "<div>\
                        <input type='checkbox' tick='getTime' onchange='POCsettingChange();' "+(set.indexOf("getTime")==-1?"":"checked")+">[T] Local time</input><br>\
                        <input type='checkbox' tick='getGMT' onchange='POCsettingChange();' "+(set.indexOf("getGMT")==-1?"":"checked")+">[G] GMT time</input><br>\
                        <input type='checkbox' tick='getAPS' onchange='POCsettingChange();' "+(set.indexOf("getAPS")==-1?"":"checked")+">[A] AP refresh</input><br>\
                        <input type='checkbox' tick='getBuildingTime' onchange='POCsettingChange();' "+(set.indexOf("getBuildingTime")==-1?"":"checked")+">[B] Building tick</input><br>\
                        <input type='checkbox' tick='getPLTime' onchange='POCsettingChange();' "+(set.indexOf("getPLTime")==-1?"":"checked")+">[P] Planet tick</input><br>\
                        <input type='checkbox' tick='getStarbaseTime' onchange='POCsettingChange();' "+(set.indexOf("getStarbaseTime")==-1?"":"checked")+">[S] Starbase tick</input><br>\
                        <input type='checkbox' tick='getNPCTime' onchange='POCsettingChange();' "+(set.indexOf("getNPCTime")==-1?"":"checked")+">[N] NPC tick</input><br>\
                        <input type='checkbox' tick='getLeechTime' onchange='POCsettingChange();' "+(set.indexOf("getLeechTime")==-1?"":"checked")+">[L] Leech repair tick</input><br>\
                        <input type='checkbox' tick='getACSTime' onchange='POCsettingChange();' "+(set.indexOf("getACSTime")==-1?"":"checked")+">[C] ACS report tick</input><br>\
                        <input type='checkbox' tick='getEMTime' onchange='POCsettingChange();' "+(set.indexOf("getEMTime")==-1?"":"checked")+">[E] EM/EC report tick</input><br>\
                        <input type='checkbox' tick='getLSMTime' onchange='POCsettingChange();' "+(set.indexOf("getLSMTime")==-1?"":"checked")+" title='Lucidi Squads, Z15 scouts and Z16 fighter move to another tile on this tick'>[LM] Lucidi Squad Move tick</input><br>\
                        <input type='checkbox' tick='getLSATime' onchange='POCsettingChange();' "+(set.indexOf("getLSATime")==-1?"":"checked")+" title='Lucidi Squads, Z15 scouts and Z16 fighter will attack you here'>[LA] Lucidi Squad Attack tick</input><br>\
                        <input type='checkbox' tick='getDruggyEff' onchange='POCsettingChange();' "+(set.indexOf("getDruggyEff")==-1?"":"checked")+">[DReff] Druggy Effect</input><br>\
                        <input type='checkbox' tick='getDruggyTime' onchange='POCsettingChange();' "+(set.indexOf("getDruggyTime")==-1?"":"checked")+">[D] Druggyness time left</input><br>\
                        <hr>\
                        <input type='checkbox' tick='realtime' onchange='POCsettingChange();' "+(set.indexOf("realtime")==-1?"":"checked")+">Realtime clock</input><br>\
                    </div>"
    
    var td = document.getElementById ('poc_first_cell')
    td.insertBefore (menu, td.firstChild);
}

function POCsettingChange (value) {
    var menu = document.getElementById ('poc_settings_panel');
    if (!menu) return;
    
    var set = "";
    var cbs = menu.getElementsByTagName("input");
    for (var i=0; i<cbs.length; i++) {
        var cb = cbs[i];
        if (cb.checked) {
            set += cb.getAttribute ("tick") + ";";
        }
    }
    localStorage.setItem ('poc_clock_settings', set);
    POCreInstallClock ();
}

function POCgetSettings () {
    var set = localStorage.getItem ("poc_clock_settings");
    if (set==null) {
        set = "getTime;getGMT;getAPS;getBuildingTime;getPLTime;getStarbaseTime;getNPCTime;";
        localStorage.setItem ('poc_clock_settings', set);
    }
    return set;
}

if (document.URL.indexOf ("main.php") != -1) {
    if (!poc_msgframe_only) {
        POCinstallClock ();
    } 
} else if (document.URL.indexOf ("msgframe.php") != -1) {
    POCinstallClockMsgframe ();
}
